<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/23
 * Time: 9:21
 */
namespace app\common\business;
use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as MysqlUser;
use think\facade\Request;
use think\Exception;

class User{
    public $userObj = null;//数据库实例
    public function __construct()
    {
        $this->userObj = new MysqlUser();
    }

    /**
     *
     * 登录逻辑
     * @param $data
     * @return array|bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function Login($data)
    {
        //判断redis是否有验证码
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if(empty($redisCode) || $redisCode !=$data['code']){
//            throw new Exception('不存在该验证码','-100');
        }
        //判断数据表中的数据 是否有用户记录
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
//        var_dump($user->id);
        if(!$user){
            $username = 'cun粉-'.$data['phone_number'];
            //不存在插入数据
            $userData = [
                'username'=>$username,
                'phone_number'=>$data['phone_number'],
                'type' =>$data['type'],
                'status'=>config('status.mysql.table_normal'),
            ];
            try{//数据库有异常需要抛出明文异常
                $this->userObj->save($userData);
                $userId =$this->userObj->id;
            }catch (\Exception $e){
                throw new Exception('数据库内部异常');
            }
        }else{
            //存在更新表的登录时间
            $username = $user->username;
            $userData = [
                'last_login_ip' =>Request::ip(),
            ];
            try{
                $this->userObj->where('id',$user->id)->save($userData);
                $userId =$this->userObj->id;
            }catch (\Exception $e){
                throw new Exception('数据库内部异常');
            }
        }
        //生成token // 此处需要判断是否已经存在 如果存在直接返回
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id' =>$user->id,
            'username' =>$username
        ];
        //保存到redis参数 名称 数据  时间
        $res = cache(config("redis.token_par").$token,$redisData,Time::userLoginExpiresTime($data['type']));//保存到redis
        return $res ? ["token" =>$token,"username"=>$username] : false;//成功放回token和name名字

    }

    /**
     * 根据id获取用户信息
     * @param $id
     * @return array
     */
    public function getNormalUserId($id){
       $user =  $this->userObj->getUserById($id);
       if(!$user || $user->status !=config("status.mysql.table_normal")){
            return [];
       }
       return $user->toArray();
    }
    /**
     * 根据用户名获取用户信息
     * @param $id
     * @return array
     */
    public function getNormalUserByUsername($username){
        $user =  $this->userObj->getUserByUsername($username);
        if(!$user || $user->status !=config("status.mysql.table_normal")){
            return [];
        }
        return $user->toArray();
    }
    public function update($id,$data,$token){
        //检查此用户id是否存在
        $user = $this->getNormalUserId($id);
        if(!$user){
            throw new Exception('不存在该用户');
        }
        //检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if($userResult && $userResult['id'] !=$id){
            throw new Exception('该用户已经存在请重新设置');
        }
//        //修改数据 用户名自修改一次（思路在数据库添加字段，更改过一次做标记后面都不能修改） token中的数据需要修改
        $redisData=[
            'id'=>$user['id'],
            'username'=>$user['username'],
        ];

        $res = cache(config("redis.token_par").$token,$redisData);
        dump($res);
        return $this->userObj->updateById($id,$data);
    }
}